﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;


namespace ExaminationSys.View.Paper
{
    public partial class PaperDetailFixedList : System.Web.UI.Page
    {
 

        private static readonly DBQuestionService DBQuestionProxy = ObjectFactory<DBQuestionService>.Create();
        private static readonly DBSubjectService DBSubjectProxy = ObjectFactory<DBSubjectService>.Create();
        private static readonly PaperSubjectQuestionService PaperSubjectQuestionProxy =   ObjectFactory<PaperSubjectQuestionService>.Create();

        public string PaperID { get { return Request.QueryString["PaperID"] != null ? Request.QueryString["PaperID"].ToString() : string.Empty; } }
        public string Title { get { return Request.QueryString["Title"] != null ? Request.QueryString["Title"].ToString() : string.Empty; } }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                PageEntity = null;
                Session.Add("queryTable", "DBQuestion");
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            lblTitle.Text = Title;
            PaperDetailFixedSearchWindow.GridStore = this.StoreDBQuestion;
            
        }

        private int pageSize = 20;
        public static PageEntity PageEntity = null;
        protected void StoreDBQuestion_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            string sqlWhere = " 1=1";
            int pageIndex = 0;
            if (PageEntity != null)
            {
                Session["queryTable"] = "all";
                sqlWhere = PageEntity.SqlWhere;
                pageIndex = 1;
            }
            else
            {
                sqlWhere += " and Status<>0";
                pageIndex = (e.Start / e.Limit) + 1;

            }

            int totalPage, totalRecord;
            if ( Session["queryTable"].ToString() == "DBQuestion")
            {
                sqlWhere += " and TableName='DBQuestion'";
                this.StoreDBQuestion.DataSource = DBQuestionProxy.GetListPageByView(sqlWhere, " OperatorTime desc", pageSize, pageIndex,
                                                                       out totalPage, out totalRecord);
            }
            else if (Session["queryTable"].ToString() == "DBSubject")
            {
                sqlWhere += " and TableName='DBSubject'";
                this.StoreDBQuestion.DataSource = DBQuestionProxy.GetListPageByView(sqlWhere, " OperatorTime desc", pageSize, pageIndex,
                                                                 out totalPage, out totalRecord);
            }
            else
            {
                this.StoreDBQuestion.DataSource = DBQuestionProxy.GetListPageByView(sqlWhere, " OperatorTime desc", pageSize, pageIndex,
                                                                out totalPage, out totalRecord);
            }
            e.Total = totalRecord;

            this.StoreDBQuestion.DataBind();
        }

    

        public void SearchFun(PageEntity pageEntity)
        {
            PageEntity = pageEntity;
        }


        protected void Command(object sender, DirectEventArgs e)
        {
            var command = e.ExtraParams["command"];

            var id = e.ExtraParams["Id"];
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBoxHelper.ShowInfo("获取ID失败");
                return;
            }

            if (command.Equals("edit", StringComparison.OrdinalIgnoreCase))
            {
               // ShowDetails(id);
            }
            else
            {
                var entity = DBQuestionProxy.Get(new Guid(id));
                if (entity != null)
                {
                    entity.Status = 0;
                    var success = DBQuestionProxy.Update(entity);
                    if (success)
                    {
                        StoreDBQuestion.Remove(entity.ID);
                        MessageBoxHelper.ShowInfo("删除成功");
                    }
                }
            }
        }
 
        [DirectMethod]
        public void DoConfirm()
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }
            X.Msg.Confirm("提示", "是否删除选中记录?", new MessageBoxButtonsConfig
            {
                Yes = new MessageBoxButtonConfig
                {
                    Handler = "X.DoDelete()",
                    Text = "是"
                },
                No = new MessageBoxButtonConfig
                {
                    Text = "否"
                }
            }).Show();
        }

        [DirectMethod]
        public void DoDelete()
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = DBQuestionProxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StoreDBQuestion.Remove(id));
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }


        /// <summary>
        /// 添加表试卷 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnAddToPaper_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要添加的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }

            

            var success = false;
            foreach (var id in ids)
            {
                if(!PaperSubjectQuestionProxy.CheckQuestionExists(new Guid(id),new Guid(PaperID)))
                {
                    PaperSubjectQuestion entity = new PaperSubjectQuestion();
                    entity.ID = Guid.NewGuid();
                    entity.QuestionID = new Guid(id);
                    entity.PaperID = new Guid(PaperID);
                    entity.QuestionType = Session["queryTable"].ToString();
                    entity.Status = 1;

                    var op = FormsAuthenticationHelper.GetCurrentUserID();
                    if (string.IsNullOrEmpty(op))
                    {
                        FormsAuthenticationHelper.SignOut();
                        Response.Redirect("~/Account/Login.aspx");
                    }
                    entity.Operator = op;
                    entity.OrderIndex = PaperSubjectQuestionProxy.GetMaxOrderIndex(new Guid(PaperID)) + 1;
                    entity.OperatorTime = DateTime.Now;

                    PaperSubjectQuestionProxy.Insert(entity);
                }
                success =true;
             
            }

            
            if (success)
            {
                ids.ForEach(id => StoreDBQuestion.Remove(id));
                MessageBoxHelper.ShowInfo("成功添加到试卷！");
            }
        }

        protected void BatchDelete_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = DBQuestionProxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StoreDBQuestion.Remove(id));
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }
        protected void BatchLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = DBQuestionProxy.Lock(ids, 1);
            if (success)
            {
                StoreDBQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchUnLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelDBQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要解锁的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = DBQuestionProxy.Lock(ids, 0);
            if (success)
            {
                StoreDBQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }


        //跳转到己选题界面
        protected void BtnGo_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperDetailFixedChosenList.aspx?PaperID=" + PaperID + "&Title=" + Title);

        }

         //跳转到试卷管理界面
        protected void BtnGoManage_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperInfoList.aspx");

        }


        //高级查找
        protected void BtnSearch_Click(object sender, DirectEventArgs e)
        {
            this.PaperDetailFixedSearchWindow.Show(SearchFun);
        }
        
        protected void BtnFind_Click(object sender, DirectEventArgs e)
        {
            var text = SearchText.Text.Trim();
            StringBuilder sqlWhere = new StringBuilder("   Status<>0  ");
            if (!string.IsNullOrWhiteSpace(text))
            {
                text = text.SqlSafe();
                StringBuilder sbWhere = new StringBuilder(" and ");
                sbWhere.Append(" Knowledge like '%{0}%' ");
                sbWhere.Append(" or KeyWord like '%{0}%' ");
                sbWhere.Append(" or QuestionType like '%{0}%' ");
                sbWhere.Append(" or DBQuestionType like '%{0}%' ");
                sbWhere.Append(" or SubjectType like '%{0}%' ");
                sbWhere.Append(" or Challenge like '%{0}%' ");
                sbWhere.Append(" or AttachFile like '%{0}%' ");
                sbWhere.Append(" or Content like '%{0}%' ");
                sqlWhere.Append(string.Format(sbWhere.ToString(), text));
            }
            PageEntity pageEntity = new PageEntity();
            pageEntity.SqlWhere = sqlWhere.ToString();
            SearchFun(pageEntity);
            StoreDBQuestion.Reload();
        }

        protected void BtnDBSubject_Click(object sender, DirectEventArgs e)
        {
            PageEntity = null;
            Session["queryTable"] = "DBSubject";
            StoreDBQuestion.Reload();
           
        }

         protected void BtnDBQustion_Click(object sender, DirectEventArgs e)
        {
            PageEntity = null;
            Session["queryTable"] = "DBQuestion";
            StoreDBQuestion.Reload();
        }

            

        public void Btn_GoBack(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperInfoList.aspx");
        }

    }
}